package com.loby.data.util;

import lombok.Data;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 树结构返回,对应antd
 * @author Alex
 */
@Data
@Accessors(chain = true)
public class BaseTree {
    private String pkId;
    private String key;
    private String parentKey;
    private String title;
    private List<BaseTree> children;
    private String  UniqueCode;
    private int status;
    private String flag;


    public static <T extends BaseTree> List<T> buildTree(List<T> recode) {
        Map<String, T> map = new LinkedHashMap<>();
        recode.forEach(r -> map.put(r.getKey(), r));
        ArrayList<T> ret = new ArrayList<>();
        for (T t : map.values()) {
            String pId = t.getParentKey();
            T p = map.get(pId);

            // 根节点
            if ("0".equals(t.getParentKey()) || p == null) {
                ret.add(t);
                continue;
            }

            if (p.getChildren() == null) {
                p.setChildren(new ArrayList<>());
            }
            p.getChildren().add(t);
        }
        return ret;
    }

}
